<template>
  <div class="user-status">
    <el-dropdown v-if="user">
      <span class="el-dropdown-link">
        <el-icon :size="20"><user /></el-icon>
        {{ user.username }}
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-if="user.type === 2" @click="handleEditProfile">修改信息</el-dropdown-item>
          <el-dropdown-item v-if="user.type === 1" @click="handleEditDoctorProfile">修改信息</el-dropdown-item>
          <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-button v-else @click="router.push('/login')">登录/注册</el-button>

    <!--TODO: 修改信息弹窗 -->
    <el-dialog title="修改信息" v-model="showEditProfile" width="50%">
      <el-form :model="currentForm" :rules="rules" ref="userFormRef">
        <el-form-item label="头像">
          <div class="content-item">
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                accept="image/jpeg,image/jpg,image/png,image/gif"
            >
              <img v-if="currentForm.avatar" :src="currentForm.avatar" class="avatar" alt="" width="100px" height="100px"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="真实姓名" prop="userRealName">
          <el-input v-model="currentForm.userRealName" placeholder="请输入真实姓名"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="currentForm.phone" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentForm.gender" placeholder="请选择性别">
            <el-option :value="0" label="男"/>
            <el-option :value="1" label="女"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditProfile = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProfile">保存</el-button>
      </template>
    </el-dialog>

    <!--TODO: 新增/编辑医生对话框 -->
    <el-dialog title="医生信息修改" v-model="doctorDialogVisible" width="50%">
      <el-form-item label="头像">
        <div class="content-item">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
              accept="image/jpeg,image/jpg,image/png,image/gif"
          >
            <img v-if="currentForm.avatar" :src="currentForm.avatar" class="avatar" alt="" width="100px" height="100px"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
      </el-form-item>
      <el-form :model="currentForm" :rules="rules" ref="doctorFormRef">
        <el-form-item label="医生姓名" prop="doctorRealName">
          <el-input v-model="currentForm.doctorRealName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="currentForm.password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="currentForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentForm.gender" placeholder="请选择性别">
            <el-option :value="0" label="男" />
            <el-option :value="1" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="currentForm.title" placeholder="请输入职称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="doctorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDoctorInfo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, ref} from 'vue';
import { useRouter } from 'vue-router';
import {getUserInfo, logout, setUserInfo} from '@/utils/auth';
import {Plus, User} from "@element-plus/icons-vue";
import {userUpdateOne} from "@/api/user.js";
import {ElMessage, ElNotification} from "element-plus";
import {BaseURL} from "@/utils/http.js";
import {doctorUpdateOne} from "@/api/doctor.js";
const showEditProfile = ref(false);
const currentForm = ref({});
const uploadUrl = BaseURL + '/upload';
const doctorDialogVisible = ref(false);

// 验证规则
const rules = {
  username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
  userRealName: [{required: true, message: '真实姓名不能为空', trigger: 'blur'}],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {type: 'email', message: '邮箱格式错误', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '电话不能为空', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '电话格式错误', trigger: 'blur'},
  ],
};

const handleAvatarSuccess = (response) => {
  if (response) {
    console.log(response);
    currentForm.value.avatar = response.data;
    console.log(currentForm.value.avatar);
    ElNotification({
      title: '上传成功',
      message: '图片上传成功',
      type:'success'
    });
  }
};

const handleAvatarError = (error) => {
  console.log(error);
  ElNotification({
    title: '上传失败',
    message: '图片上传失败',
    type: 'error'
  });
}

const beforeAvatarUpload = (rawFile) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
  if (!allowedTypes.includes(rawFile.type)) {
    ElMessage.error('头像图片必须是 JPG、JPEG、PNG、GIF 格式！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('头像图片大小不能超过 5MB！')
    return false
  }
  return true
}

const router = useRouter();
const user = computed(() => getUserInfo());

const handleLogout = () => {
  logout();
  router.push('/login');
};



const handleEditProfile = () => {
  showEditProfile.value = true;
  currentForm.value = user.value;
};

const handleEditDoctorProfile = () => {
  doctorDialogVisible.value = true;
  currentForm.value = user.value;
}

const handleSaveProfile = async () => {
  // TODO: 实现修改信息功能
  const res = await userUpdateOne(currentForm.value);
  if (res.code === 200) {
    ElMessage.success('修改成功');
    setUserInfo(currentForm.value);
    showEditProfile.value = false;
    currentForm.value = {};
  }
};

const saveDoctorInfo = async () => {
  // TODO: 实现新增/编辑医生功能
  const res = await doctorUpdateOne(currentForm.value);
  if (res.code === 200) {
    ElMessage.success('修改成功');
    doctorDialogVisible.value = false;
    currentForm.value = {};
  }
};
</script>

<style scoped>
.user-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}
</style>
